#ifndef SHAPE_H
#define SHAPE_H

#include <QObject>
#include <QPainter>
#include <QTextLayout>
#include <QDebug>

class Shape : public QObject
{
    Q_OBJECT
public:

    enum Shapes
    {
        none = 0,
        line,
        rect,
        text
    };

    explicit Shape(int type, QObject* parent, const QColor& color, int penWidth);
    virtual ~Shape();

    int Type()
    {
        return m_Type;
    }

    virtual void Paint(QPainter* painter) = 0;
    virtual void SetStartPoint(QPoint pt) = 0;
    virtual void SetEndPoint(QPoint pt) = 0;

private:
    int m_Type;
protected:
    QColor m_penColor;
    int m_nPenWidth;
};

class Line : public Shape
{
public:
    explicit Line(QObject* parent, const QColor& color, int penWidth);
    virtual ~Line();

    virtual void Paint(QPainter* painter);
    virtual void SetStartPoint(QPoint pt);
    virtual void SetEndPoint(QPoint pt);
private:
    QList<QPoint> m_points;

};

class Rect : public Shape
{
public:
    explicit Rect(QObject* parent, const QColor& color, int penWidth);
    virtual ~Rect();

    virtual void Paint(QPainter* painter);
    virtual void SetStartPoint(QPoint pt);
    virtual void SetEndPoint(QPoint pt);
public:
    QPoint ptStart;
    QPoint ptEnd;
    bool m_bHasEnd;
};

class LineText : public Shape
{
public:
    explicit LineText(QObject* parent, const QColor& color, const QFont &font);
    virtual ~LineText();

    virtual void Paint(QPainter* painter);
    virtual void SetStartPoint(QPoint pt);
    virtual void SetEndPoint(QPoint pt);

    void SetFont(const QFont &font);
    void AppendText(const QString &text);
    void SetEdit(bool bEdit);
    int TextLength() const;
    void MoveCursor(int step);
    void BackSpace();
    void Delete();
    void Home();
    void End();
    QRectF TextRect()
    {
        QTextLine line = m_textLayout.lineAt(0);
        int pos = line.horizontalAdvance();
        const int nTextLength = m_text.length();
        if (nTextLength > 1 && m_nCursorPos != nTextLength)
        {
            pos = line.horizontalAdvance()/nTextLength*m_nCursorPos;
        }
        return QRectF(QPointF(ptStart.x() + pos, ptStart.y()),
                      QSize(line.width(), line.height()));
    }

    QString Text()
    {
        return m_text;
    }

    int CursorPositon()
    {
        return m_nCursorPos;
    }

    QFont Font()
    {
        return m_font;
    }
private:
    void UpdateTextRect();
    void UpdateCursorPos();
    void UpdateLayout();
public:
    //绘制文字的左上角坐标
    QPoint ptStart;
//    QPoint ptEnd;
//    bool m_bHasEnd;
    QFont m_font;
    QString m_text;
    bool m_bEdit;
    uint m_nWidth;
    uint m_nHeight;
    int m_nCursorPos;
    uint m_nCursorX;
    //文字上升高度
    int m_nAscent;
    QTextLayout m_textLayout;
};

#endif // SHAPE_H
